import requests
import pprint
import re
import os

url = ' https://pvp.qq.com/web201605/js/herolist.json'
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36'
}

response = requests.get(url, headers=headers)
data_json = response.json()

for index in data_json:
    hero_id = index['ename']
    hero_name = index['cname']
    path = f'{hero_name}\\'
    if not os.path.exists(path):
        os.mkdir(path)

    index_url = f'https://pvp.qq.com/web201605/herodetail/{hero_id}.shtml'

    requests_1 = requests.get(url=index_url, headers=headers)
    requests_1.encoding = requests_1.apparent_encoding  # 自动转码

    name_list = re.findall('data-imgname="(.*?)"', requests_1.text)[0]

    name = re.sub('&\d+', '', name_list).split('|')  # 替换 分割

    for i in range(1, int(len(name)) + 1):
        link_url = f'https://game.gtimg.cn/images/yxzj/img201606/skin/hero-info/{hero_id}/{hero_id}-bigskin-{i}.jpg'
        img_name = name[int(i) - 1]

        img_content = requests.get(url=link_url, headers=headers).content
        with open(path + img_name + '.jpg', mode='wb') as f:
            f.write(img_content)
            # print(link_url)
            print(img_name)

# pprint.pprint(response.json())      # 格式化输出
